// miniprogram/views/goods/payOrder/payOrder.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sku: [],
    openid: "oSLcM5LGwyD0ah5-YthisY9E0Wqw",
    goods: [],
    user: {},
    order: {},
    slecetBlance: true,
    text: '',
  },
  goGoodDetail: function (e) {
    wx.navigateTo({
      url: '/views/goods/detail/detail?id=' + e.currentTarget.dataset.id,
    })
  },
  goAddress: function (e) {
    return;
    wx.navigateTo({
      url: '/views/userCenter/addresses/addresses',
    })
  },
  GetOrderNumber() {
    var randomNum = "";
    for (var i = 0; i < 14; i++) //j位随机数，用以加在时间戳后面。
    {
      randomNum += Math.floor(Math.random() * 10);
    }
    randomNum = new Date().getTime() + randomNum;
    return randomNum;
  },
  checkboxChange: function (e) {
    // var that = this;
    // var order = that.data.order;
    // if (e.detail.value.length == 0) {
    //   order.balancePay = 0;
    //   that.setData({
    //     slecetBlance: false,
    //     text: "支付0元,剩余" +
    //       (that.data.user.balance) + "元"
    //   });
    // } else {
    //   that.setData({
    //     slecetBlance: true,
    //     text: '支付' + that.data.order.balancePay + "元,剩余" +
    //       (that.data.user.balance - that.data.order.balancePay) + "元"
    //   });
    //   if (order.totalPrice > that.data.user.balance) {
    //     order.balancePay = that.data.user.balance;
    //   } else {
    //     order.balancePay = order.totalPrice;
    //   }
    // }
    // order.weiChatPay = order.totalPrice - order.balancePay;
    // that.setData({
    //   order: order
    // });
  },
  /**
   * 提交订单
   */
  submitOrder: function () {
    var that = this;

    if (that.data.user == undefined) {
      wx.showModal({
        title: '提示',
        content: '请先添加收货地址',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/views/userCenter/address-edit/address-edit',
            })

          } else if (res.cancel) {

            wx.navigateTo({
              url: '/views/userCenter/address-edit/address-edit',
            })
          }
        }
      })
    }
    wx.showLoading({
      title: '正在请求微信支付...',
      icon: "loading",
      mask: true,
      duration: 2000,
      complete: function () {

        setTimeout(() => {
          wx.showModal({
            title: '提示',
            content: '尚未接入微信支付,是否模拟订单提交?',
            success(res) {
              if (res.confirm) {
                var db = wx.cloud.database();
                var order = that.data.order;
                order.submitTime = db.serverDate();
                that.data.goods.forEach(c => {
                  order.items.push({
                    goodsId: c.goods[0]._id,
                    count: c.count,
                    price: c.goods[0].price
                  });
                });
                db.collection("order").add({
                  data: that.data.order
                });

                wx.navigateTo({
                  url: '/views/userCenter/orderList/orderList?state=0',
                })
              } else if (res.cancel) {}
            }
          })
        }, 2000);
      }
    })
    wx.requestPayment({
      timeStamp: '',
      nonceStr: '',
      package: '',
      signType: 'MD5',
      paySign: '',
      success(res) {},
      fail(res) {}
    })
  },
  payment: function (data) {
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType,
      'paySign': data.paySign,
      'success': function (res) {
        console.log("s");
        console.log(res);
      },
      'fail': function (res) {
        console.log("f");
        console.log(res);
      },
      'complete': function (res) {
        console.log("c");
        console.log(res);
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      openid: options.openid == undefined ? options.openid : "oSLcM5LGwyD0ah5-YthisY9E0Wqw"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this;
    var b = 0;

    try {
      var value = wx.getStorageSync('cart');
      debugger;
      if (value) {
        that.setData({
          goods:value,
        });
      }
    } catch (e) {
      // Do something when catch error
    }
    var totalPrice = 0;
    var goods = that.data.goods;
    goods.forEach(x => {
      totalPrice += (x.count * x.price);
    });

    that.setData({
      order: {
        totalPrice: parseFloat(totalPrice.toFixed(2)),
        balancePay: 0,
        weiChatPay: (totalPrice - b),
        couponPay: 0,
        state: 0,
        orderNumber: that.GetOrderNumber(),
        submitTime: '',
        items: []
      },
      slecetBlance: true,
      text: '支付' + parseFloat(b.toFixed(2)) + "元,剩余" +
        (totalPrice - b) + "元"
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})